<?php
declare(strict_types=1);

namespace SixShop\PHPInfo\Middleware;

use Closure;
use think\DbManager;
use think\Request;
use think\Response;


class AppendSqlDebugMiddleware
{
    private array $logList = [];

    public function __construct(private readonly DbManager $dbManager)
    {
        $this->dbManager->setLog(function (string $type, string $log) {
            $this->logList[] = $log;
        });
    }

    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        if ($response instanceof Response && is_array($data = $response->getData())) {
            $data['sql'] = $this->logList;
            if (!empty($data['sql'])) {
                $response->data($data);
            }
        }

        return $response;
    }
}